﻿#-*- coding: utf-8 -*-
from PyQt4.QtGui import QApplication, QWidget, QPainter, QPixmap, QFont
from PyQt4.QtCore import pyqtSignal, QUrl, QString, Qt
from PyQt4.QtNetwork import QNetworkAccessManager, QNetworkRequest

url = "http://maps.google.com/maps/api/staticmap?center=Brooklyn+Bridge,New+York,NY&zoom=14&size=512x512&maptype=roadmap&markers=color:blue|label:S|40.702147,-74.015794&markers=color:green|label:G|40.711614,-74.012318&markers=color:red|color:red|label:C|40.718217,-73.998284&sensor=false"



class GoogleMapsWidget(QWidget):
    url_changed = pyqtSignal()
    loading_changed = pyqtSignal()

    def __init__(self, url=None, parent=None):
        super(GoogleMapsWidget, self).__init__(parent)
        self._url = QUrl(url)
        self.imagem = None
        self.loading = self._url is not None
        if self._url:
            self.download_imagem()
        self.url_changed.connect(self.download_imagem)
        self.loading_changed.connect(self.update)
        
    @property
    def url(self):
        return self._url
    @url.setter
    def url(self, nova_url):
        self._url = QUrl(nova_url)
        self.loading = True
        self.url_changed.emit()
    
    @property
    def loading(self):
        return self._loading
    @loading.setter
    def loading(self, status):
        self._loading = status
        self.loading_changed.emit()
    
    def download_imagem(self):
        manager = QNetworkAccessManager(self)
        manager.finished.connect(self.atualiza_imagem)
        manager.get(QNetworkRequest(self._url))
        
    def atualiza_imagem(self, reply):
        dados = reply.readAll()
        pixmap = QPixmap()
        pixmap.loadFromData(dados)
        self.imagem = pixmap
        reply.deleteLater()
        self.resize(pixmap.size())
        self.loading = False
        
    def paintEvent(self, event):
        if self.loading:
            painter = QPainter(self)
            painter.setFont(QFont("Arial", 30))
            painter.drawText(self.rect(), Qt.AlignCenter, QString("Carregando..."))
        elif self.imagem:
            painter = QPainter(self)
            painter.drawPixmap(self.rect(), self.imagem)
        else:
            super(GoogleMapsWidget, self).paintEvent(event)

    def mouseDoubleClickEvent(self, event):
        url = "http://maps.google.com/maps/api/staticmap?center=40.714728,-73.998672&zoom=14&size=400x400&sensor=false"
        self.url = url
        
app = QApplication([])
g = GoogleMapsWidget(url)
g.show()
app.exec_()
